package com.chookss.home.publish.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.BuildConfig;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.LogEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.bigImage.ImagePreview;
import com.chookss.tools.bigImage.bean.ImageInfo;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.VideoOnePlayActivity;
import com.chookss.video.entity.VideoEntity;
import com.chookss.view.MyRoundLayout;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyImagsAdapter extends BaseQuickAdapter<LogEntity.VideoBean, BaseViewHolderEx> {
    private Context context;
    private int width, height;
    private List<ImageInfo> imageInfoList = new ArrayList<>();
    private int type = 0;//3发布模式，可以修改 但是不能查看大图不能播放视频  1 发布成功正常详情页可以0发布中的详情页不得操作

    public MyImagsAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<LogEntity.VideoBean> data, int type) {
        super(layoutResId, data);
        this.context = context;
        width = (Utils.getScreenWidthPixel(context) - Utils.dip2px(context, 48)) / 3;
        height = width;
        this.type = type;
        if (type == 1) {

        }
    }

    public void setUrlList(List<ImageInfo> imageInfoList) {
        this.imageInfoList=imageInfoList;
    }

    @Override
    protected void convert(BaseViewHolderEx helper, LogEntity.VideoBean item) {
        MyRoundLayout myRl = helper.getView(R.id.myRl);
        ImageView ivBg = helper.getView(R.id.ivBg);
        ImageView ivVideo = helper.getView(R.id.ivVideo);
        ImageView ivBf = helper.getView(R.id.ivBf);
        LinearLayout llDelete = helper.getView(R.id.llDelete);
        LinearLayout llAdd = helper.getView(R.id.llAdd);
        TextView tvUpload = helper.getView(R.id.tvUpload);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myRl.getLayoutParams();
        params.height = height;
        params.width = width;
        myRl.setLayoutParams(params);
        RelativeLayout.LayoutParams llAddParams = (RelativeLayout.LayoutParams) llAdd.getLayoutParams();
        llAddParams.height = height;
        llAddParams.width = width;
        llAdd.setLayoutParams(llAddParams);
        llAdd.setVisibility(View.GONE);
        myRl.setVisibility(View.VISIBLE);
        if (type == 3) {
            llDelete.setVisibility(View.VISIBLE);
            tvUpload.setVisibility(View.GONE);
        } else {
            llDelete.setVisibility(View.GONE);
            if (type == 0) {
                tvUpload.setVisibility(View.VISIBLE);
            } else {
                tvUpload.setVisibility(View.GONE);
            }

        }
        if ("1".equals(item.getType())) {
            //视频
            ivVideo.setVisibility(View.VISIBLE);
            ivBf.setVisibility(View.VISIBLE);
            ivBg.setVisibility(View.GONE);
            if(item.getVideoCoverPath().startsWith("http")||item.getVideoCoverPath().endsWith("JPEG")){
                GlideUtils.load(context, item.getVideoCoverPath(), ivVideo, R.drawable.default_news);
            }else{
                if(!Utils.isNull(item.getVideoCoverPath())){
                    Uri vedioUri = null;
                    File vedio = new File(item.getVideoCoverPath());
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                        vedioUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", vedio);
                    } else {
                        vedioUri = Uri.fromFile(vedio);
                    }
                    Bitmap bitmap=getVideoThumb(context, vedioUri);
                    if(bitmap==null){
                        Glide.with(context).load(R.drawable.default_vedio).into(ivVideo);
                    }else{
                        Glide.with(context).load(getVideoThumb(context, vedioUri)).into(ivVideo);
                    }
                }else{
                    Glide.with(context).load(R.drawable.default_vedio).into(ivVideo);
                }

            }
        } else {
            //图片
            ivVideo.setVisibility(View.GONE);
            ivBf.setVisibility(View.GONE);
            ivBg.setVisibility(View.VISIBLE);
            GlideUtils.load(context, item.getUrl(), ivBg, R.drawable.default_news);
            KLog.i(item.getUrl());
        }
        myRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == 1) {
                    if ("0".equals(item.getType())) {
                        if(imageInfoList.size()>0){
                            ImagePreview
                                    .getInstance()
                                    // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好；
                                    .setContext(context)
                                    // 设置从第几张开始看（索引从0开始）
                                    .setIndex(helper.getItemPosition())
                                    .setShowCloseButton(true)
                                    .setLoadStrategy(ImagePreview.LoadStrategy.NetworkAuto)
                                    .setImageInfoList(imageInfoList)
                                    .start();
                        }

                    } else if ("1".equals(item.getType())) {
                        getVideo(item.getVideoId());
                    }
                }else  if (type == 0){
                    MyToast.show("附件上传中");
                }
            }
        });
        llDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<>();
                map.put("position", helper.getItemPosition() + "");
                map.put("deletePicVideo", "deletePicVideo");
                EventBus.getDefault().post(new MyEvent(map));

            }
        });
    }

    private void getVideo(String id) {
        Map<String, String> map = new HashMap<>();
        map.put("videoId", id);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<VideoEntity>>() {
        }.getType(), null, Urls.selectAPPVideoById, SignUtils2.makeSignStr(map), false, new ObserverCallback<VideoEntity>() {
            @Override
            public void onSuccess(VideoEntity data) {
                if (Utils.isNull(data.videoId)) {
                    MyToast.show("视频id为空");
                    return;
                }
                Intent intent = new Intent(context, VideoOnePlayActivity.class);
                intent.putExtra("watermark", "2");
                intent.putExtra("video", data);
                context.startActivity(intent);
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    /**
     * @param context
     * @param uri
     * @return 获取视频第一帧
     */
    public static Bitmap getVideoThumb(Context context, Uri uri) {
        Bitmap bitmap=null;
        MediaMetadataRetriever media = null;
        try {
            media = new MediaMetadataRetriever();
            media.setDataSource(context, uri);
            bitmap= media.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            bitmap=null;
        } catch (SecurityException e) {
            e.printStackTrace();
            bitmap=null;
        }
        return bitmap;
    }
}
